var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    let username = $("#username").val()
    console.log(`username = ${username}`)

    let socket = new SockJS('/spring-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        //订阅 websocket的一个目标
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
        //订阅 websocket的发给自己的目标
        if (username) {
            stompClient.subscribe(`/user/${username}/chart`, function (greeting) {
                showGreeting(JSON.parse(greeting.body).content, true);
            });
        }
    });
}

function sendName() {
    stompClient.send("/app/echo", {}, JSON.stringify({'name': $("#name").val()}));
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}


function showGreeting(message, secret) {
    if (secret) {
        $("#greetings").append("<tr style='color: darkgoldenrod'><td>" + message + "</td></tr>");
    } else {
        $("#greetings").append("<tr><td>" + message + "</td></tr>");
    }

}

function login() {
    let username = $("#username").val()
    $("#member").text(username)
    $("#loginForm").hide()
    $("#usernameDiv").show()
}

$(function () {
    $("#loginForm").show()
    $("#usernameDiv").hide()
    $("#inputDiv").hide()


    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); $("#inputDiv").show();});
    $( "#disconnect" ).click(function() { disconnect(); $("#inputDiv").hide();});
    $( "#send" ).click(function() { sendName(); });

    $( "#login" ).click(function() { login(); });
});